﻿using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace ldhWebApiIIS.filters
{
    public class UApiKeyFilterAttribute : ActionFilterAttribute
    {
        public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            StringValues ukey;
            if (context.HttpContext.Request.Headers.TryGetValue("u-apikey", out ukey))
            {
                if (ukey.FirstOrDefault() == "111")
                {
                    return base.OnActionExecutionAsync(context, next);
                }
            }
           return Task.Run(() => { Challenge(context.HttpContext); });
        }

        void Challenge(HttpContext actionContext)
        {
            actionContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
        }
    }
}
